package com.itcast.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itcast.mapper.CategoryMapper;
import com.itcast.pojo.service.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    public List<Category> findAllCategory() {
        QueryWrapper<Category> queryWrapper = Wrappers.query();
        List<Category> categoryList = categoryMapper.selectList(queryWrapper);
        ArrayList<Category> list = new ArrayList<>();
        for (Category category : categoryList) {
            if (category.getPid() == 0) {
                list.add(category);
            }
        }
        return list;
    }

    public List<Category> findCategoryByCodeOrName(String code, String name,Integer pid) {
        Category category = new Category();
        category.setCode(code);
        category.setName(name);
        category.setPid(pid);
        QueryWrapper<Category> queryWrapper = Wrappers.query(category);
        List<Category> categoryList = categoryMapper.selectList(queryWrapper);
        return categoryList;
    }

    /**
     * 添加
     */
    public void addCategory(Category category) {
        category.setPid(0);
        categoryMapper.insert(category);
    }

    public void deleteCategory(Integer id) {
        Category category = new Category();
        category.setPid(id);
        QueryWrapper<Category> queryWrapper = Wrappers.query(category);
        List<Category> categoryList = categoryMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(categoryList)){
            categoryMapper.deleteById(id);
        }else {
            throw new RuntimeException("该分类有子分类，不能删除");
        }
    }

    /**
     * 修改分类
     */
    public void updateCategory(Category category) {
        categoryMapper.updateById(category);
    }
}
